/*
 * Created by SharpDevelop.
 * User: nebulom
 * Date: 9/2/2009
 * Time: 8:03 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.Windows.Forms;
using Buaya.Model;
using System.Collections.Generic;

namespace Buaya.Gui
{
	/// <summary>
	/// Description of DeductionForm.
	/// </summary>
	public partial class DeductionForm : BaseForm
	{
		public DeductionForm() : this(new List<Deduction>())
		{
			
		}
		
		public DeductionForm(IList<Deduction> d)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			listView1.Resize += delegate { columnHeader1.Width = listView1.Width - 22 -(columnHeader2.Width + columnHeader3.Width + columnHeader4.Width); };
			Model = d;
		}
		
		protected override void OnModelChanged(EventArgs e)
		{
			base.OnModelChanged(e);
			IList<Deduction> d = Model as IList<Deduction>;
			DeductionAdded += delegate { RefreshList(); };
		}
		
		void RefreshList()
		{
			listView1.Items.Clear();
			foreach (Deduction d in Model as IList<Deduction>) {
				ListViewItem li = listView1.Items.Add(d.Employee.Name.ToString());
				li.SubItems.Add(d.PayrollCode.Code);
				li.SubItems.Add(d.Date.ToShortDateString());
				li.SubItems.Add(d.Amount.ToString("0.00"));
			}
		}
		
		public virtual void AddDeduction(Deduction d)
		{
			(Model as IList<Deduction>).Add(d);
			OnDeductionAdded(null);
		}
		
		protected virtual void OnDeductionAdded(EventArgs e)
		{
			if (DeductionAdded != null) {
				DeductionAdded(this, e);
			}
		}
		
		public virtual event EventHandler DeductionAdded;
		
		void ButtonSaveAndCloseClick(object sender, EventArgs e)
		{
			Save();
			Close();
		}
		
		void Save()
		{
			foreach (Deduction d in Model as IList<Deduction>) {
				SessionFacade.SaveOrUpdateDeduction(d);
			}
		}
		
		void ButtonSaveAndClearClick(object sender, EventArgs e)
		{
			Save();
			ButtonClearClick(sender, e);
		}
		
		void ButtonClearClick(object sender, EventArgs e)
		{
			Model = new List<Deduction>();
		}
		
		void ContextMenuStrip1Opening(object sender, System.ComponentModel.CancelEventArgs e)
		{
			
		}
		
		void NewToolStripMenuItemClick(object sender, EventArgs e)
		{
			using (DeductionEmployeeForm f = new DeductionEmployeeForm()) {
				if (MainForm.Instance.AddDialog(f) == DialogResult.OK) {
					AddDeduction(f.Model as Deduction);
				}
			}
		}
	}
}
